package com.macaline.service.impl.perssion;

import com.macaline.bean.Result;
import com.macaline.entity.Permission;
import com.macaline.entity.Role;
import com.macaline.entity.RolePermission;
import com.macaline.mapper.RoleMapper;
import com.macaline.mapper.RolePermissionMapper;
import com.macaline.service.base.BaseService;
import com.macaline.service.perssion.PermissionService;
import com.macaline.service.perssion.RoleService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@Service
public class RoleServiceimpl implements RoleService {
	
	@Resource
	RoleMapper roleMapper;

	@Resource
	RolePermissionMapper rolePermissionMapper;

	@Resource
	PermissionService permissionService;
	
	/**
	 * 
	* <p>@author warm_joy </p>
	* <p>Description: 通过id查询角色信息</p>
	* <p>Date: 2019-06-22 14:42</p>
	* @param id 需要查询角色信息的id
	* @return
	 */
	@Override
	@Cacheable(value = "role", key = "#id")
	public Role queryById(Integer id) {
		Role role = roleMapper.selectById(id);
		if(role == null){
			return null;
		}
		return role;
	}

	/**
	 * 添加一个角色
	 * @param role 要添加的角色信息
	 * @return
	 */
	@Override
	public Object add(Role role) {
		int insert = roleMapper.insert(role);
		if(insert != 1){
			return Result.error("添加失败");
		}
		return Result.success();
	}

	@Override
	public List<Permission> getPermssionByRoleId(int roleId) {
		Role role = roleIdIsOk(roleId);
		if(role == null){
			return null;
		}
		List<RolePermission> rolePermissionList = rolePermissionMapper.getPermissionByRoleId(roleId);
		List<Integer> idList = new LinkedList<Integer>();
		for (RolePermission rolePermission : rolePermissionList){
			idList.add(rolePermission.getPermissionId());
		}
		List<Permission> list = permissionService.getPermissionListByIds(idList);
		if(list.size() < 1){
			return null;
		}
		return list;
	}

	/**
	 * 为一个角色添加权限
	 * @return
	 */
	@Override
	public int addPermissionToRole(RolePermission rolePermission) {
		int i = rolePermissionMapper.addPermissionToRole(rolePermission);
		return i;
	}

	/**
	 * 校验角色ID是否合法
	 * 如果合法返回该ID的角色信息，不合法返回null。
	 * @param roleId 校验的参数ID
	 * @return
	 */
	public Role roleIdIsOk(Integer roleId){
		Role role = roleMapper.selectById(roleId);
		return role;
	}

}
